package com.scnu.api.config;

import com.scnu.common.constants.Constant;
import com.scnu.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;

public class DefaultFeignConfig {

    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.FULL;
    }

/*    @Bean
    @Order(500)
    public RequestInterceptor userInfoRequestInterceptor(){
        return template -> {
//            Long userId = UserContext.getUser();
            Long userId = UserContext.getUserId();
            if (userId != null){
                template.header("user-id", userId.toString());
            }

        };
    }
    @Bean
    @Order(0)
    public RequestInterceptor requestIdInterceptor(){
        return template -> template
                .header(Constant.REQUEST_ID_HEADER, MDC.get(Constant.REQUEST_ID_HEADER))
                .header(Constant.REQUEST_FROM_HEADER, Constant.FEIGN_ORIGIN_NAME);
    }*/


    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return new OrderedRequestInterceptor(100) {
            @Override
            public void apply(RequestTemplate template) {
//                Long userId = UserContext.getUserId();
                Integer userId = UserContext.getUserId();
                if (userId != null){
                    template.header("user-id", userId.toString());
                }
            }
        };
    }
    @Bean
    public RequestInterceptor requestIdInterceptor(){
        return new OrderedRequestInterceptor(Ordered.HIGHEST_PRECEDENCE) {
            @Override
            public void apply(RequestTemplate template) {
                template.header(Constant.REQUEST_ID_HEADER, MDC.get(Constant.REQUEST_ID_HEADER))
                        .header(Constant.REQUEST_FROM_HEADER, Constant.FEIGN_ORIGIN_NAME);
            }
        };
    }





    // 自定义一个带序号的 RequestInterceptor 父类
    public static abstract class OrderedRequestInterceptor implements RequestInterceptor, Ordered {
        private final int order;
        public OrderedRequestInterceptor(int order) {
            this.order = order;
        }
        public OrderedRequestInterceptor() {
            this(Ordered.LOWEST_PRECEDENCE);
        }
        @Override
        public int getOrder() {
            return order;
        }
    }

}
